<template>
  <div class="app-container">
    <!-- 顶部搜索和操作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名称"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        <el-button type="primary" icon="el-icon-upload2" size="mini" @click="handleUpload">上传文件</el-button>
        <el-button type="success" icon="el-icon-connection" size="mini" @click="handleFtpCollect">FTP文件采集</el-button>
      </el-form-item>
    </el-form>

    <!-- 筛选与排序 -->
    <el-row :gutter="10" class="status-row">
      <el-col :span="12">
        <el-radio-group v-model="queryParams.fileType" @change="handleQuery" size="medium">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button label="pdf">PDF</el-radio-button>
          <el-radio-button label="image">图像</el-radio-button>
          <el-radio-button label="doc">文档</el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="12" class="right-actions">
        <el-dropdown @command="handleSort">
          <el-button size="mini" icon="el-icon-sort">排序</el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="uploadTime">按上传时间</el-dropdown-item>
            <el-dropdown-item command="fileName">按文件名</el-dropdown-item>
            <el-dropdown-item command="fileSize">按文件大小</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-card class="table-card" shadow="hover">
      <el-table
        v-loading="loading"
        :data="fileList"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
        :cell-style="{ padding: '12px 0' }"
      >
        <el-table-column label="文件名称" align="center" min-width="180">
          <template slot-scope="scope">
            <div class="file-name">
              <i :class="getFileIcon(scope.row.fileType)" class="file-icon"></i>
              {{ scope.row.fileName }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="病历ID" align="center" prop="recordId" min-width="140" />
        <el-table-column label="患者姓名" align="center" prop="uploadUser" min-width="100" />
        <el-table-column label="文件类型" align="center" min-width="100">
          <template slot-scope="scope">
            {{ getFileTypeText(scope.row.fileType) }}
          </template>
        </el-table-column>
        <el-table-column label="大小" align="center" min-width="100">
          <template slot-scope="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="采集时间" align="center" min-width="160">
          <template slot-scope="scope">
            {{ parseTime(scope.row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-download"
              circle
              title="下载"
              @click="handleDownload(scope.row)"
            ></el-button>
            <el-button
              v-if="canPreview(scope.row.fileType)"
              size="mini"
              type="info"
              icon="el-icon-view"
              circle
              title="预览"
              @click="handlePreview(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 文件上传对话框 -->
    <el-dialog title="上传电子病历文件" :visible.sync="uploadOpen" width="500px" append-to-body>
      <el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="100px">
        <el-form-item label="病历ID" prop="recordId">
          <el-input v-model="uploadForm.recordId" placeholder="请输入关联病历ID" />
        </el-form-item>
        <el-form-item label="文件描述" prop="fileDesc">
          <el-input v-model="uploadForm.fileDesc" placeholder="请输入文件描述信息" />
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="upload"
            :limit="1"
            :file-list="uploadFileList"
            :on-change="handleFileChange"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传PDF/Word/Excel/图片等文件，且不超过10MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload">确 定</el-button>
        <el-button @click="cancelUpload">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览对话框 -->
    <el-dialog :title="previewTitle" :visible.sync="previewOpen" width="80%" top="5vh" append-to-body>
      <div class="preview-container">
        <!-- PDF预览 -->
        <iframe v-if="isPdf(previewInfo.fileType)" :src="previewUrl" width="100%" height="600px" frameborder="0"></iframe>
        <!-- 图片预览 -->
        <img v-else-if="isImage(previewInfo.fileType)" :src="previewUrl" style="max-width:100%; max-height:600px;" />
        <!-- 其他格式提示下载 -->
        <div v-else class="no-preview">
          <i class="el-icon-document"></i>
          <p>该文件类型不支持在线预览，请下载后查看</p>
          <el-button type="primary" @click="handleDownload(previewInfo)">下载文件</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- FTP文件采集对话框 -->
    <el-dialog title="FTP文件采集" :visible.sync="ftpCollectOpen" width="550px" append-to-body>
      <div class="ftp-info-box">
        <div class="ftp-info-item">
          <span class="label">FTP服务器:</span>
          <span class="value">140.140.1.30:2121</span>
        </div>
        <div class="ftp-info-item">
          <span class="label">用户名/密码:</span>
          <span class="value">jiahe/jiahe</span>
        </div>
        <div class="ftp-info-item">
          <span class="label">采集规则:</span>
          <span class="value">采集txt和word文件类型</span>
        </div>
        <div class="ftp-info-item">
          <span class="label">文件路径规则:</span>
          <span class="value">如 IN_MR_SN="ZM0.000.00B.780" → 路径为"ZM/00/00/00/B7/80"</span>
        </div>
      </div>

      <div class="ftp-collect-options">
        <el-form ref="ftpCollectForm" :model="ftpCollectForm" label-width="100px">
          <el-form-item label="采集类型" prop="collectType">
            <el-radio-group v-model="ftpCollectForm.collectType">
              <el-radio label="all">全部记录</el-radio>
              <el-radio label="date">按日期范围</el-radio>
              <el-radio label="custom">自定义条件</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="ftpCollectForm.collectType === 'date'" label="日期范围" prop="dateRange">
            <el-date-picker
              v-model="ftpCollectForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>

          <el-form-item v-if="ftpCollectForm.collectType === 'custom'" label="病历编号" prop="mrCode">
            <el-input v-model="ftpCollectForm.mrCode" placeholder="请输入病历编号"></el-input>
          </el-form-item>

          <el-form-item label="最大采集数" prop="maxCount">
            <el-input-number v-model="ftpCollectForm.maxCount" :min="1" :max="1000" style="width: 160px"></el-input-number>
            <span class="help-text">限制单次最大采集文件数量</span>
          </el-form-item>
        </el-form>
      </div>

      <div class="collect-progress" v-if="collectProgress.show">
        <p>正在采集文件，请稍候...</p>
        <el-progress :percentage="collectProgress.percent" :text-inside="true" :stroke-width="18"></el-progress>
        <p>{{ collectProgress.message }}</p>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="startFtpCollect" :loading="collectProgress.show">开始采集</el-button>
        <el-button @click="ftpCollectOpen = false" :disabled="collectProgress.show">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { getToken } from "@/utils/auth";
import { listFiles, downloadFile, getPreviewUrl, uploadFile, collectFilesFromFtp, getFtpCollectStatus } from "@/api/ai/fileManagement";
import Pagination from "@/components/Pagination";

export default {
  name: "FileManagement",
  components: { Pagination },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 显示搜索条件
      showSearch: true,
      // 文件列表
      fileList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: "",      // 文件名称搜索
        fileType: "",      // pdf/image/doc
        sortField: "uploadTime", // 排序字段
        sortOrder: "desc",  // 排序方向
      },
      // 上传参数
      headers: { Authorization: "Bearer " + getToken() },
      uploadOpen: false,
      uploadUrl: process.env.VUE_APP_BASE_API + "/ai/file/upload",
      uploadFileList: [],
      uploadForm: {
        recordId: "",
        fileDesc: "",
        file: undefined
      },
      uploadRules: {
        recordId: [{ required: true, message: "请输入关联病历ID", trigger: "blur" }],
        file: [{ required: true, message: "请选择要上传的文件", trigger: "change" }]
      },
      // 预览参数
      previewOpen: false,
      previewTitle: "",
      previewInfo: {},
      previewUrl: "",
      // FTP采集参数
      ftpCollectOpen: false,
      ftpCollectForm: {
        collectType: "all",
        dateRange: [],
        mrCode: "",
        maxCount: 100
      },
      collectProgress: {
        show: false,
        percent: 0,
        message: ""
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文件列表 */
    getList() {
      this.loading = true;
      listFiles(this.queryParams).then(response => {
        if (response.code === 0) {
          this.fileList = response.data.records;
          this.total = response.data.total;
        } else {
          this.$message.error("获取文件列表失败：" + response.msg);
          this.fileList = [];
          this.total = 0;
        }
        this.loading = false;
      }).catch(error => {
        console.error("获取文件列表失败", error);
        this.$message.error("获取文件列表失败：" + error);
        this.loading = false;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        fileName: "",
        fileType: "",
        sortField: "uploadTime",
        sortOrder: "desc"
      };
      this.getList();
    },

    /** 处理排序 */
    handleSort(field) {
      if (this.queryParams.sortField === field) {
        this.queryParams.sortOrder = this.queryParams.sortOrder === "asc" ? "desc" : "asc";
      } else {
        this.queryParams.sortField = field;
        this.queryParams.sortOrder = "desc";
      }
      this.getList();
    },

    /** 处理导出 */
    handleExport() {
      this.$confirm('确认导出所有文件记录?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$message.success("导出成功");
        // 实际项目中调用导出API
      }).catch(() => {});
    },

    /** 格式化文件大小 */
    formatFileSize(bytes) {
      if (bytes === 0) return "0 B";
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    /** 根据文件类型获取图标 */
    getFileIcon(fileType) {
      if (this.isPdf(fileType)) {
        return "el-icon-document";
      } else if (this.isImage(fileType)) {
        return "el-icon-picture";
      } else if (this.isExcel(fileType)) {
        return "el-icon-s-grid";
      } else if (this.isWord(fileType)) {
        return "el-icon-document-copy";
      } else {
        return "el-icon-document";
      }
    },

    /** 根据文件类型获取文本描述 */
    getFileTypeText(fileType) {
      if (this.isPdf(fileType)) {
        return "PDF文档";
      } else if (this.isImage(fileType)) {
        return "图像文件";
      } else if (this.isExcel(fileType)) {
        return "Excel文档";
      } else if (this.isWord(fileType)) {
        return "Word文档";
      } else if (fileType.includes("zip") || fileType.includes("rar") || fileType.includes("7z")) {
        return "压缩包";
      } else {
        return "其他文档";
      }
    },

    /** 判断是否PDF文件 */
    isPdf(fileType) {
      return fileType && fileType.toLowerCase().includes("pdf");
    },

    /** 判断是否图片文件 */
    isImage(fileType) {
      return fileType && (
        fileType.toLowerCase().includes("image") ||
        fileType.toLowerCase().includes("jpg") ||
        fileType.toLowerCase().includes("jpeg") ||
        fileType.toLowerCase().includes("png") ||
        fileType.toLowerCase().includes("gif")
      );
    },

    /** 判断是否Excel文件 */
    isExcel(fileType) {
      return fileType && (
        fileType.toLowerCase().includes("excel") ||
        fileType.toLowerCase().includes("spreadsheet") ||
        fileType.toLowerCase().includes("xlsx") ||
        fileType.toLowerCase().includes("xls")
      );
    },

    /** 判断是否Word文件 */
    isWord(fileType) {
      return fileType && (
        fileType.toLowerCase().includes("word") ||
        fileType.toLowerCase().includes("document") ||
        fileType.toLowerCase().includes("docx") ||
        fileType.toLowerCase().includes("doc")
      );
    },

    /** 判断文件是否可以预览 */
    canPreview(fileType) {
      return this.isPdf(fileType) || this.isImage(fileType);
    },

    /** 处理上传 */
    handleUpload() {
      this.uploadOpen = true;
      this.uploadForm = {
        recordId: "",
        fileDesc: "",
        file: undefined
      };
      this.uploadFileList = [];
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
    },

    /** 上传前检查 */
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传文件大小不能超过 10MB!");
        return false;
      }
      this.uploadForm.file = file;
      return true;
    },

    /** 上传文件个数超出限制 */
    handleExceed() {
      this.$message.warning("最多只能上传1个文件");
    },

    /** 提交上传 */
    submitUpload() {
      this.$refs.uploadForm.validate(valid => {
        if (valid) {
          if (!this.uploadForm.file) {
            this.$message.error("请先选择要上传的文件");
            return;
          }

          // 创建FormData对象
          const formData = new FormData();
          formData.append("file", this.uploadForm.file);
          formData.append("recordId", this.uploadForm.recordId);
          formData.append("fileDesc", this.uploadForm.fileDesc);

          // 调用上传API
          uploadFile(formData).then(response => {
            if (response.code === 0) {
              this.$message.success("上传成功");
              this.uploadOpen = false;
              this.getList();
            } else {
              this.$message.error("上传失败: " + response.msg);
            }
          }).catch(error => {
            this.$message.error("上传失败: " + error);
          });
        }
      });
    },

        /** 处理文件变更 */
    handleFileChange(file) {
      if (file && file.raw) {
        this.uploadForm.file = file.raw;
        this.uploadFileList = [file];
      }
    },

    /** 取消上传 */
    cancelUpload() {
      this.uploadOpen = false;
      this.uploadForm = {
        recordId: "",
        fileDesc: "",
        file: undefined
      };
      this.uploadFileList = [];
    },

    /** 处理下载 */
    handleDownload(row) {
      this.$message.success("文件 " + row.fileName + " 下载中...");
      downloadFile(row.id).then(response => {
        const url = window.URL.createObjectURL(new Blob([response]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', row.fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        this.$message.success("文件下载成功");
      }).catch(error => {
        this.$message.error("文件下载失败: " + error);
      });
    },

        /** 处理预览 */
    handlePreview(row) {
      if (!this.canPreview(row.fileType)) {
        this.$message.warning("该文件类型不支持在线预览");
        return;
      }

      this.previewInfo = row;
      this.previewTitle = row.fileName;
      this.previewOpen = true;

      // 从后端获取文件的预览URL
      getPreviewUrl(row.id).then(response => {
        if (response.code === 0 && response.data) {
          this.previewUrl = response.data;
        } else {
          this.$message.error("获取预览地址失败：" + response.msg);
          this.previewOpen = false;
        }
      }).catch(error => {
        this.$message.error("获取预览地址失败: " + error);
        this.previewOpen = false;
      });
    },

    /** 处理FTP文件采集 */
    handleFtpCollect() {
      this.ftpCollectOpen = true;
      this.ftpCollectForm = {
        collectType: "all",
        dateRange: [],
        mrCode: "",
        maxCount: 100
      };
      this.collectProgress = {
        show: false,
        percent: 0,
        message: ""
      };
    },

    /** 开始FTP文件采集 */
    startFtpCollect() {
      this.$refs.ftpCollectForm.validate(valid => {
        if (valid) {
          this.collectProgress.show = true;
          this.collectProgress.percent = 0;
          this.collectProgress.message = "正在连接FTP服务器...";

          // 构建请求参数
          const params = {
            collectType: this.ftpCollectForm.collectType,
            maxCount: this.ftpCollectForm.maxCount,
            ftpConfig: {
              host: "140.140.1.30",
              port: 2121,
              username: "jiahe",
              password: "jiahe"
            }
          };

          // 添加可选参数
          if (this.ftpCollectForm.collectType === 'date' && this.ftpCollectForm.dateRange.length === 2) {
            params.startDate = parseTime(this.ftpCollectForm.dateRange[0], '{y}-{m}-{d}');
            params.endDate = parseTime(this.ftpCollectForm.dateRange[1], '{y}-{m}-{d}');
          } else if (this.ftpCollectForm.collectType === 'custom') {
            params.mrCode = this.ftpCollectForm.mrCode;
          }

          // 调用API开始采集
          collectFilesFromFtp(params).then(response => {
            if (response.code === 0) {
              const taskId = response.data;
              // 启动轮询检查任务状态
              this.pollFtpTaskStatus(taskId);
            } else {
              this.collectProgress.show = false;
              this.$message.error("启动FTP采集任务失败: " + response.msg);
            }
          }).catch(error => {
            this.collectProgress.show = false;
            this.$message.error("启动FTP采集任务失败: " + error);
          });
        }
      });
    },

    /** 轮询FTP采集任务状态 */
    pollFtpTaskStatus(taskId) {
      const checkStatus = () => {
        getFtpCollectStatus(taskId).then(response => {
          if (response.code === 0) {
            const taskStatus = response.data;

            // 更新进度
            this.collectProgress.percent = taskStatus.percent || 0;
            this.collectProgress.message = taskStatus.message || "正在采集文件...";

            // 检查任务是否完成
            if (taskStatus.status === 'COMPLETED') {
              this.collectProgress.message = `采集完成！共采集 ${taskStatus.totalFiles || 0} 个文件`;
              this.collectProgress.percent = 100;
              this.$message.success("FTP文件采集成功！");
              this.getList(); // 刷新文件列表
              this.collectProgress.show = false;
            } else if (taskStatus.status === 'FAILED') {
              this.collectProgress.message = "采集失败: " + (taskStatus.errorMsg || "未知错误");
              this.$message.error("FTP文件采集失败");
              this.collectProgress.show = false;
            } else {
              // 任务还在进行中，继续轮询
              setTimeout(checkStatus, 2000);
            }
          } else {
            this.collectProgress.message = "获取任务状态失败: " + response.msg;
            this.$message.error("获取任务状态失败");
            this.collectProgress.show = false;
          }
        }).catch(error => {
          this.collectProgress.message = "获取任务状态失败: " + error;
          this.$message.error("获取任务状态失败");
          this.collectProgress.show = false;
        });
      };

      // 开始轮询
      checkStatus();
    }
  }
};
</script>

<style scoped>
.status-row {
  margin-top: 10px;
  margin-bottom: 15px;
}
.right-actions {
  text-align: right;
}
.file-name {
  display: flex;
  align-items: center;
  justify-content: center;
}
.file-icon {
  margin-right: 8px;
  font-size: 16px;
}
.preview-container {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.no-preview {
  text-align: center;
  padding: 40px;
}
.no-preview i {
  font-size: 48px;
  color: #909399;
  margin-bottom: 20px;
}
.ftp-info-box {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.ftp-info-item {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.ftp-info-item .label {
  font-weight: bold;
  color: #303133;
}
.ftp-info-item .value {
  color: #606266;
  word-break: break-all;
}
.ftp-collect-options {
  margin-bottom: 20px;
}
.collect-progress {
  text-align: center;
  padding: 20px;
}
.collect-progress p {
  margin-bottom: 10px;
  color: #606266;
}
.help-text {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}
</style>
